package org.sjs.dreamfly.common.util

import android.content.Context
import android.widget.Toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.sjs.dreamfly.app.DreamFlyApplication
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.io.IOException


object PhemonUtils {

    fun TODO(reason: String) {
        Toast.makeText(getApplication(), "TODO:$reason", Toast.LENGTH_SHORT).show()
    }

    fun getApplication(): DreamFlyApplication {
        return DreamFlyApplication.instance
    }

    suspend fun saveFile(context: Context, path: String, content: String) = withContext(Dispatchers.IO) {
        LogUtil.d(path)
        try {
            val file = File(path)
            val outputStream = FileOutputStream(file)
            outputStream.write(content.toByteArray())
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    suspend fun loadFile(context: Context, path: String): String = withContext(Dispatchers.IO) {
        val file = File(path)
        val stringBuilder = StringBuilder()
        try {
            val reader = FileReader(file)
            val bufferedReader = BufferedReader(reader)
            var line: String?

            while (bufferedReader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
            bufferedReader.close()
            reader.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return@withContext stringBuilder.toString()
    }

    fun getScreenWidth(): Int {
        return getApplication().resources.displayMetrics.widthPixels
    }

    fun formatTime(milliseconds: Long): String {
        val totalSeconds = milliseconds / 1000
        val hours = totalSeconds / 3600
        val minutes = (totalSeconds % 3600) / 60
        val seconds = totalSeconds % 60
        return String.format("%02d:%02d:%02d", hours, minutes, seconds)
    }
}